﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using FeedReader.Shared.Data;
using FeedReader.Shared.Extensions;

namespace FeedReader.Shared.Workers
{
    public class StorageWorker
    {
        CloudStorageAccount acc;

        public StorageWorker(CloudStorageAccount theacc)
        {
            acc = theacc;
        }

        public void StoreFeed(Feed thefeed, string userid)
        {
            //move declerations to  class scope
            FeedsDataSource feedtable = new FeedsDataSource(acc);
            PostsDataSource PostTable = new PostsDataSource(acc);
            BlogIDDataSource blogidsource = new BlogIDDataSource(acc);
            CloudBlobClient theblobclient = acc.CreateCloudBlobClient();
            CloudBlobContainer postfiles = theblobclient.GetContainerReference(ContainerNameServices.Posts);
            UserSubscrptionsDataSource usersubstable = new UserSubscrptionsDataSource(acc);
            postfiles.CreateIfNotExist();
            bool feedexists = BlobNameServices.Exists(blogidsource,thefeed.URL);

            if (feedexists == false)
            {
                //extension method?
                FeedsDataModel dataitem = new FeedsDataModel();
                dataitem.DateTime = thefeed.DateTime.ToString();
                dataitem.Description = thefeed.Description;
                dataitem.HtmlURL = thefeed.URL;
                dataitem.RssURL = "";
                dataitem.Title = thefeed.Title;
                dataitem.CloudEnabled = false;
                dataitem.BlogID = BlobNameServices.CreateBlobEntry(thefeed.URL, blogidsource);

                feedtable.Insert(dataitem);

                //can we LINQ this?
                foreach (Post thepost in thefeed.Posts)
                {
                    PostsDataModel post = new PostsDataModel();
                    string hash=System.Web.HttpUtility.UrlPathEncode(Utils.HashToBase64(thepost.Title));
                    string postid = dataitem.BlogID + hash.Replace("+","0");
                    CloudBlob theblob = postfiles.GetBlobReference(postid);
                    theblob.UploadText(thepost.Content);
                    
                    post.BlogID = dataitem.BlogID;
                    post.PostID = postid;
                    post.PublishDate = thepost.PublishedTime.UtcDateTime;
                    post.TheBlobID = postid;
                    post.Title = thepost.Title;
                    post.URL = post.URL;

                    PostTable.Insert(post);
                }
            }
            else // too verbose
            {
                string blobid = BlobNameServices.getBlobID(blogidsource, thefeed.URL);
                List<Post> currentPosts = new List<Post>();
                
                IEnumerable<Post> results;
                try
                {
                    DateTimeOffset cutoff;
                     cutoff= currentPosts.OrderByDescending(C => C.PublishedTime).ElementAt(0).PublishedTime;// assuming the posts are in chronological order
                    int beforecount = thefeed.Posts.Count();// we don't use this at all
                     results= thefeed.Posts.Where(C => C.PublishedTime.isLaterThan(cutoff));
                }
                catch
                {
                    results = thefeed.Posts;
                }

                    
                
                foreach (Post thepost in results)
                {
                    PostsDataModel post = new PostsDataModel();
                    string postid = blobid + Utils.HashToBase64(thepost.Title);//url encode this
                    CloudBlob theblob = postfiles.GetBlobReference(postid);
                    theblob.UploadText(thepost.Content);

                    post.BlogID = blobid;
                    post.PostID = postid;
                    post.PublishDate = thepost.PublishedTime.UtcDateTime;
                    post.TheBlobID = postid;
                    post.Title = thepost.Title;
                    post.URL = post.URL;

                    PostTable.Insert(post);
                }
                
                //List<Post> newpostlist= new List<Post>(currentPosts.Union(results)); //not needed - we are not returning any items from ths method

                
            }

            UserSubscrptionsDataModel newsub = new UserSubscrptionsDataModel(); // adding the new subscription should be done in the backend. 

            newsub.BlogID = BlobNameServices.getBlobID(blogidsource, thefeed.URL);     // however could thi simpact performance? IE - laging?
            newsub.UserID = userid;
            usersubstable.Insert(newsub);

        }

        public void StoreUpdateFeed(Feed thefeed)
        {
            PostsDataSource PostTable = new PostsDataSource(acc);
            BlogIDDataSource blogidsource = new BlogIDDataSource(acc);
            CloudBlobClient theblobclient = acc.CreateCloudBlobClient();
            CloudBlobContainer postfiles = theblobclient.GetContainerReference(ContainerNameServices.Posts);

            string blobid = BlobNameServices.getBlobID(blogidsource, thefeed.URL);
            List<Post> currentPosts = new List<Post>();

            IEnumerable<Post> results;
            try
            {
                DateTimeOffset cutoff;
                cutoff = currentPosts.OrderByDescending(C => C.PublishedTime).ElementAt(0).PublishedTime;// assuming the posts are in chronological order
                int beforecount = thefeed.Posts.Count();// we don't use this at all
                results = thefeed.Posts.Where(C => C.PublishedTime.isLaterThan(cutoff));
            }
            catch
            {
                results = thefeed.Posts;
            }



            foreach (Post thepost in results)
            {
                PostsDataModel post = new PostsDataModel();
                string postid = blobid + Utils.HashToBase64(thepost.Title);//url encode this
                CloudBlob theblob = postfiles.GetBlobReference(postid);
                theblob.UploadText(thepost.Content);

                post.BlogID = blobid;
                post.PostID = postid;
                post.PublishDate = thepost.PublishedTime.UtcDateTime;
                post.TheBlobID = postid;
                post.Title = thepost.Title;
                post.URL = post.URL;

                PostTable.Insert(post);
            }
        }

        public void StoreOPMLItems(IQueryable<OPMLItem> items, string username)
        {
            FeedFetcher fetcher = new FeedFetcher();
            foreach(OPMLItem item in items){
                Feed thefeed = fetcher.FetchFeed(item.RssURL);
                StoreFeed(thefeed,username);
            }
        }
    }
}
